from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from test_data.data import test_data


class DriverManager:

    def __init__(self, name='chrome'):
        if name == 'chrome':
            service = Service(test_data.chromedriver_path)  # 创建服务  指定谷歌驱动文件地址
            self.dr = webdriver.Chrome(service=service)
        elif name == 'firefox':
            self.dr = webdriver.Firefox()

    def refresh(self):
        try:
            handles = self.dr.window_handles
            self.dr.switch_to.window(handles[0])
        except Exception:
            self.dr = DriverManager().dr
        else:
            # 只留一个窗口
            while len(handles) > 1:
                self.dr.close()
                handles = self.dr.window_handles
                self.dr.switch_to.window(handles[0])
            if 'data:,' != self.dr.current_url:
                # 清除缓存
                dm.dr.get('chrome://settings/clearBrowserData')
                sleep(1)
                clearButton = dm.dr.execute_script(
                    "return document.querySelector('settings-ui').shadowRoot.querySelector("
                    "'settings-main').shadowRoot.querySelector("
                    "'settings-basic-page').shadowRoot.querySelector('settings-section > "
                    "settings-privacy-page').shadowRoot.querySelector("
                    "'settings-clear-browsing-data-dialog').shadowRoot.querySelector("
                    "'#clearBrowsingDataDialog').querySelector("
                    "'#clearBrowsingDataConfirm')")
                clearButton.click()

    # def scroll_right(self, pixels):
    #     self.dr.execute_script(f"window.scrollBy({pixels}, 0);")


# 初始化driver对象
dm = DriverManager()
